import ws from "ws";

var log = console.log;

export class LNode {
    /** 
     * 代理名称
     */
    name: string = "";

    /**
     * socket 节点
     */
    socket !: ws;
    /**
     * 创建时间
     */
    createTime: number = 0;
    /**
     * 
     */
    host: string = "";
    port: number = 0;

    offtimes: number = 0;

    /**
     * 是否 从属
     * 主从关系，从属向主人发送ping
     */
    isSalve: boolean = false;

    constructor(socket?: ws) {
        if (socket) {
            this.socket = socket;
            // TODO: 这里要补充 host 和port
        }
        this.createTime = Date.now();
    }

    async connect(host: string, port: number) {
        return new Promise<boolean>((resolve, reject) => {
            let webScock = new ws(`ws://${host}:${port}`);
            webScock.on("open", () => {
                this.socket = webScock;
                resolve(true);
            });
            webScock.on("error", () => {
                resolve(false);
            });
            webScock.on("close", (code: number, reason: string) => {
                this.onClose(code, reason);
                resolve(false);
            });
            webScock.on("message", (data: ws.Data) => {
                // lyu.adapter.onReceive(this, data);
                resolve(true);
            });
        });
    }

    /**
     * 客户端节点关闭
     */
    onClose(code: number, reason: string) {
        // lyu.adapter.removeNode(this.name);
    }

    async send(data: any) {
        return new Promise<any>((resolve, reject) => {
            let t = JSON.stringify(data);
            this.socket.send(t, { compress: true }, (err) => {
                resolve(err);
            });
        });
    }
}